package club.justwill.single.Service.impl;

import club.justwill.single.Service.ActivityService;
import club.justwill.single.Tools;
import club.justwill.single.bean.Activity.CreateActivity;
import club.justwill.single.bean.Activity.JoinActivity;
import club.justwill.single.bean.SearchActivity;
import club.justwill.single.helper.FileHelper;
import club.justwill.single.impl.ToolsImpl;
import club.justwill.single.model.ActivityStatus;
import club.justwill.single.model.CoreConstants;
import club.justwill.single.model.JsonResponse;
import club.justwill.single.model.SecurityToken;
import club.justwill.single.persistence.dao.ActivityDao;
import club.justwill.single.persistence.dao.UserActivityDao;
import club.justwill.single.persistence.dao.UserDao;
import club.justwill.single.persistence.jpo.Activity;
import club.justwill.single.persistence.jpo.User;
import club.justwill.single.persistence.jpo.UserActivity;
import club.justwill.single.util.JsonResponseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by xiangnan on 16-1-15.
 */
@Service
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class ActivityServiceImpl extends BaseService implements ActivityService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private ActivityDao activityDao;

    @Autowired
    private UserActivityDao userActivityDao;

    @Autowired
    private FileHelper fileHelper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, noRollbackFor = Throwable.class, readOnly = false)
    public Activity createActivity(SecurityToken token, JsonResponse obj, CreateActivity createActivity) {
        User user = userDao.getById(token.getOperatorUserId());
        Timestamp actTime = ToolsImpl.deserializeTimeStamp(createActivity.getActivityTime());
        if(!token.isMoreThanConsumer()) {
            JsonResponseHelper.addError(obj, CoreConstants.AUTHORITY_ERROR);
        } else if (actTime.before(new Date())) {
            JsonResponseHelper.addError(obj, CoreConstants.DATE_ERROR);
        } else if (user == null || user.getUserId() == 0) {
            JsonResponseHelper.addError(obj, CoreConstants.PLEASE_LOGIN);
        } else {
            Activity activity = new Activity();
            activity.setUserId(token.getOperatorUserId());
            activity.setName(createActivity.getName());
            activity.setActivityDescription(createActivity.getActivityDescription());
            activity.setActiTime(actTime);
            activity.setStatus(ActivityStatus.NORMAL);
            activity.setAddress(createActivity.getAddress());
            activityDao.save(activity, token);
            return activity;
        }
        return null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, noRollbackFor = Throwable.class, readOnly = false)
    public void joinActivity(SecurityToken token, JsonResponse obj, Long activityId) {
        Activity activity = activityDao.getByActId(activityId);
        User user = userDao.getById(token.getOperatorUserId());
        UserActivity userActivity = userActivityDao.getByUser8ActivityId(token.getOperatorUserId(), activityId);
        if (user == null || user.getUserId() == 0) {
            JsonResponseHelper.addError(obj, CoreConstants.PLEASE_LOGIN);
        } else if (activity == null || activity.getActivityId() == 0) {
            JsonResponseHelper.addError(obj, CoreConstants.ACTIVITY_NOT_EXIST);
        } else if (userActivity != null) {
            JsonResponseHelper.addError(obj, CoreConstants.USER_ACTIVITY_EXIST);
        } else {
            userActivity = new UserActivity();
            userActivity.setUserId(user.getUserId());
            userActivity.setActivityId(activity.getActivityId());
            userActivity.setStatus(ActivityStatus.NORMAL);
            userActivityDao.save(userActivity, token);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, noRollbackFor = Throwable.class, readOnly = false)
    public Map<String, List> getActivity(SecurityToken token, JsonResponse obj) {
        User user = userDao.getById(token.getOperatorUserId());
        Map<String, List> activityMap = new HashMap<String, List>();
        if (user == null || user.getUserId() == 0) {
            JsonResponseHelper.addError(obj, CoreConstants.PLEASE_LOGIN);
        } else {
            List activityList = activityDao.getByUserId(user.getUserId());
            Set<UserActivity> joinUserActivitySet = user.getUserActivitySet();
            List<Long> joinActivityIdList = new ArrayList<Long>();
            for(UserActivity userActivity : joinUserActivitySet) {
                joinActivityIdList.add(userActivity.getActivityId());
            }
            if (!ToolsImpl.isEmpty(joinActivityIdList)) {
                List joinActivityList = activityDao.getByActIdList(joinActivityIdList);
                activityMap.put("join", joinActivityList);
            }
            activityMap.put("create", activityList);
        }
        return activityMap;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, noRollbackFor = Throwable.class, readOnly = false)
    public void uploadActivityCover(SecurityToken token, JsonResponse obj, CommonsMultipartFile activityCover, Long activityId) {
        String path = fileHelper.saveFile(activityCover);
        if (path == null || "".equals(path)) {
            JsonResponseHelper.addError(obj, CoreConstants.FILE_UPLOAD_FAILED);
        } else {
            Activity activity = activityDao.getByActId(activityId);
            if (activity == null) {
                JsonResponseHelper.addError(obj, CoreConstants.ACTIVITY_NOT_EXIST);
            } else {
                activity.setCover(path);
                activityDao.update(activity, token);
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, noRollbackFor = Throwable.class, readOnly = false)
    public List<Activity> searchActivity(JsonResponse obj, SearchActivity searchActivity) {
        if (searchActivity.getIndex() < 0) {
            JsonResponseHelper.addError(obj, CoreConstants.INDEX_ERROR);
        } else if (searchActivity.getSize() <=0) {
            JsonResponseHelper.addError(obj, CoreConstants.SIZE_ERROR);
        } else {
            List<Activity> activityList = activityDao.searchActivity(searchActivity.getIndex(), searchActivity.getSize());
            return activityList;
        }
        return null;
    }
}
